/* eslint-disable react-refresh/only-export-components */
import type { FC } from 'react'
import { useEffect, useRef } from 'react'
import { Steps, message, FloatButton, Modal } from 'antd'
import { ClearOutlined } from '@ant-design/icons'
import { getCateListApi } from '@/api/cate-api.ts'
import to from 'await-to-js'
import useArtAddStore, { selectCurrent, ArticleSteps, setCurrent, clearArticle, resetCurrent } from '@/store/art-add-store.ts'
import type { ArtAddStore } from '@/store/art-add-store.ts'
import ArticleBase from '@/components/article-add/art-base'
import ArticleCover from '@/components/article-add/art-cover'
import ArticleContent from '@/components/article-add/art-content'
import ArticleResult from '@/components/article-add/art-result'
import { postArticleApi } from '@/api/article-api.ts'
import localforage from '@/utils/localforage'
import type { StorageValue } from 'zustand/middleware'
import { defer } from 'react-router-dom'

// 步骤条的数据源
export const stepsItem = [
  {
    title: '基本信息'
  },
  {
    title: '文章封面'
  },
  {
    title: '文章内容'
  },
  {
    title: 'Done'
  }
]

const ArticleAdd: FC = () => {
  const current = useArtAddStore(selectCurrent)
  const hydrated = useArtAddStore((state) => state.hydrated)
  const modalRef = useRef<() => void>()

  useEffect(() => {
    return () => modalRef.current && modalRef.current()
  }, [])

  const handleClean = () => {
    modalRef.current = Modal.confirm({
      title: '操作提示',
      content: '此操作将清空所填写的文章内容，确认清空吗？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        clearArticle()
        resetCurrent()
        message.success('表单已清空！')
      }
    }).destroy
  }

  return (
    hydrated && (
      <div>
        <Steps size="small" current={current} items={stepsItem} />

        <div style={{ marginTop: 20 }}>
          {current === ArticleSteps.base && <ArticleBase />}
          {current === ArticleSteps.cover && <ArticleCover />}
          {current === ArticleSteps.content && <ArticleContent />}
          {current === ArticleSteps.done && <ArticleResult />}
        </div>

        {/* 浮动按钮 */}
        <FloatButton type="primary" icon={<ClearOutlined />} tooltip="清空表单" onClick={handleClean} />
      </div>
    )
  )
}

export default ArticleAdd

export const loader = async () => {
  const localData = await localforage.getItem<StorageValue<ArtAddStore>>('art-add-store')
  const current = localData?.state.current
  if (current === ArticleSteps.done) {
    // 清空文章
    clearArticle()
    // 重置 current
    resetCurrent()
  }

  // 获取分类的列表数据
  const res = getCateListApi()
  return defer({ cates: res })
}

export const action = async () => {
  const article = useArtAddStore.getState().article

  // 转换请求体数据
  const fd = new FormData()
  for (const k in article) {
    fd.append(k, article[k])
  }

  const [err] = await to(postArticleApi(fd))
  if (err) return null
  setCurrent()
  const msg = article.state === '草稿' ? '草稿保存成功！' : '文章发布成功！'
  sessionStorage.setItem('msg', msg)
  message.success(msg)
  clearArticle()
  return null
}
